﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using PaperSystem.Models;
using Webdiyer.WebControls.Mvc;

namespace PaperSystem.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        AdminRepository _adminRepository;
        PublicRepository _publicRepository;
        public AdminController()
        {
            _adminRepository = new AdminRepository();
            _publicRepository = new PublicRepository();
        }

        //管理员显示
        public ActionResult Management(QueryInfo info,int? page)
        {
            //验证cookie
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                TempData["errorMessage"] = "请先登录，再操作";
                return RedirectToAction("Index", "Login");
            }
            else
            {
                string userId = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string role = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).UserData;
                if (role != "管理员")
                {
                    TempData["errorMessage"] = "用户角色改变，请再登录";
                    return RedirectToAction("Index", "Login");
                }
                ViewData["userName"] = _publicRepository.UserName(userId, role);
            }//end 验证cookie
            ViewData["DropdownList"] = _adminRepository.CreateDropdownList();
            List<UserList> userList = _adminRepository.GetList(info);
            //用于分页
            PagedList<UserList> plist = new PagedList<UserList>(userList, page ?? 1, 20);
            if (Request.IsAjaxRequest())
                return PartialView(plist);
            return View(plist);
        }

        //添加用户
        public ContentResult Insert(string id, string name, string password, string role)
        {
            if (_adminRepository.AddUser(id, name, password, role))
                return Content("添加成功");
            else
                return Content("添加失败（请检查添加的内容）");
        }

        //修改用户信息
        [HttpPost]
        public ContentResult Update(string id, string name, string password, string role)
        {
            if (_adminRepository.UpdateUser(id, name, password, role))
                return Content("更新成功");
            else
                return Content("更新失败（请检查更新的内容）");
        }

        //删除用户
        public ContentResult Delete(string deleteRows)
        {
            if (_adminRepository.DeleteUsers(deleteRows))
                return Content("删除成功");
            else
                return Content("删除失败");
        }
    }
}
